
package jzService.msg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MessageItem {

	private String							equipmentCode;

	private HashMap<String, MessageData>	headerMap	= new HashMap<String, MessageData>();
	private List<MessageData>				messages	= new ArrayList<MessageData>();

	public MessageItem(String equipmentCode) {
		this.equipmentCode = equipmentCode;
	}

	public String getEquipmentCode() {
		return equipmentCode;
	}

	public void add(MessageData msg) {
		synchronized (this) {
			if (messages.size() > 5000) {
				messages.remove(0);
			}
			int idx = -1;
			MessageData data = headerMap.get(msg.getHeader());
			if (data != null) {
				idx = messages.indexOf(data);
				messages.remove(data);
				headerMap.remove(data.getHeader());
			}
			headerMap.put(msg.getHeader(), msg);
			if (idx < 0) {
				messages.add(msg);
			} else {
				messages.add(idx, msg);
			}
		}
	}

	public MessageData pop() {
		synchronized (this) {
			if (!messages.isEmpty()) {
				MessageData data = messages.remove(0);
				headerMap.remove(data.getHeader());
				return data;
			}
			return null;
		}
	}
}
